package com.polaris.live.ui.live.fragment

import android.os.Bundle
import android.view.View
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.R.color
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst.CALL_ANSWER_PAG
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.FragmentCallAnswerBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.im.manager.ImCallManager
import com.polaris.live.im.sfs.COMMAND_CALL_CANCEL
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.MessageMorePopup
import com.polaris.live.popup.WeekStarBlockPopup
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.ui.live.widget.listener.OnBackPressedListener
import com.polaris.live.ui.live.widget.listener.OnCallAnswerListener
import com.polaris.live.utils.OtherUserCacheUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.image.loadImage
import com.polaris.live.viewmodel.live.CallAnswerViewModel
import org.libpag.PAGScaleMode

/**
 * 接听方
 *
 * @author Created by lucas on 2023/11/14 10:11
 */
class CallAnswerFragment : BaseVbFragment<CallAnswerViewModel, FragmentCallAnswerBinding>(),
    OnBackPressedListener {

    private val mCallMessage by lazy {
        arguments?.getParcelable<CallSignalingMessage>(LiveConst.Params.CALL_MESSAGE)
            ?: throw IllegalArgumentException("callMessage is null")
    }

    private var mOnCallAnswerListener: OnCallAnswerListener? = null

    private var infoOtherResp: InfoOtherResp? = null

    private var mute: Boolean = false //是否禁言
    private var ban: Boolean = false  //是否封号

    private fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .titleBarMarginTop(mBinding.rlContent)
            .init()

        NavigationBarUtils.setNavigationHeight(mBinding.rlContent)
    }

    @field:LiveConst.CallAnswerType
    private var operateType: Int? = null

    override fun initView(savedInstanceState: Bundle?) {
        initImmersionBar()

        mViewModel.getInfoTies(mCallMessage.sender)
        mBinding.nickName.text = mCallMessage.nickname
        Glide.with(this)
            .loadImage(mCallMessage.cover ?: mCallMessage.avatar)
            .centerCrop()
            .into(mBinding.userHead)

        mBinding.country.setCountry(mCallMessage.country)
        mBinding.language.setLanguage(mCallMessage.language)
        mBinding.vipView.setVipLevel(mCallMessage.vipLevel)
        if (mCallMessage.getCallVo()?.starCall == true) {
            mBinding.starView.visibility = View.VISIBLE
        } else {
            mBinding.starView.visibility = View.GONE
        }

        if (mCallMessage.earnings == 0L) {
            mBinding.ivFree.visibility = View.VISIBLE
        } else {
            mBinding.ivFree.visibility = View.GONE
        }

        mBinding.pagAnswer.apply {
            path = CALL_ANSWER_PAG
            setRepeatCount(-1)
            setScaleMode(PAGScaleMode.Zoom)
            play()
        }

        initObserver()
        initListener()
    }

    private fun initObserver() {
        mViewModel.answerTimeoutLiveData.observe(this) {
            mViewModel.callEnd(
                mCallMessage.callId,
                LiveConst.CloseType.TIMEOUT,
                UserManager.getUserId()
            )
        }
        mViewModel.callEndLiveData.observe(this) {
            mOnCallAnswerListener?.refuseCall()
        }
        mViewModel.answerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (operateType == LiveConst.AnswerType.AGREE) {
                    mOnCallAnswerListener?.agreeCall(it)
                } else {
                    mOnCallAnswerListener?.refuseCall()
                }
            }, {
                if (operateType == LiveConst.AnswerType.AGREE) {
                    ToastGravity.showGravity(it.errorMsg)
                } else {
                    mOnCallAnswerListener?.refuseCall()
                }
            })

            operateType = null
        }

        ImCallManager.observe(this, { mCallMessage.callId }) {
            withMessage<CallSignalingMessage>(COMMAND_CALL_CANCEL) {
                mOnCallAnswerListener?.refuseCall()
            }
        }
        mViewModel.infoLiveData.observe(this) { resultState ->
            parseState(resultState, {
                infoOtherResp = it
                mBinding.nickName.setNicknameColor(
                    it.decoration?.nicknameColor,
                    color.white
                )
                mute = it.flag.mute
            }, {
                when (it.errCode) {
                    CommonConst.ErrorCode.USER_LOGGED_OUT, //用户已注销
                    CommonConst.ErrorCode.ACCOUNT_SHUT_DOWN,
                    -> {//该账号已经被关小黑屋
                        OtherUserCacheUtils.removeUser(mCallMessage.sender)
                    }
                }
            })
        }
    }

    private fun initListener() {
        mBinding.llRefuse.setOnSingleClickListener {
            if (mCallMessage.earnings == 0L) {
                WeekStarBlockPopup.showPop(requireContext(), mCallMessage.sender) {
                    refuseCall()
                }
            } else {
                refuseCall()
            }
        }
        mBinding.llAgree.setOnSingleClickListener {
            StartLiveProxy.permissionVideo(requireContext(), {
                agreeCall()
            })
        }

        //更多
        mBinding.moreSelect.setOnSingleClickListener {
            val blocked = infoOtherResp?.relation?.blocked

            XPopup.Builder(requireContext())
                .isDestroyOnDismiss(true)
                .asCustom(
                    MessageMorePopup(
                        requireContext(),
                        mViewModel,
                        infoOtherResp?.userId ?: 0,
                        mute,
                        ban,
                        blocked ?: false,
                        {
                            infoOtherResp?.nickname?.let { it1 ->
                                GlobalPopupManager.showReport(
                                    requireContext(), it1,
                                    mViewModel, mCallMessage.sender, mCallMessage.callId
                                )
                            }
                        }, {
                            GlobalDialogManager.showBlackIt(
                                requireContext(),
                                mViewModel,
                                blocked ?: false,
                                mCallMessage.nickname,
                                mCallMessage.sender
                            ) { black ->
                                infoOtherResp?.relation?.blocked = black
                            }
                        }, {
                            mute = it
                        }, {
                            ban = it
                        }, {})
                )
                .show()
        }
    }

    override fun initData() {
        mViewModel.launchAnswerTimeout()
    }

    private fun agreeCall() {
        if (operateType != null) {
            return
        }
        operateType = LiveConst.AnswerType.AGREE.apply {
            mViewModel.answerCall(mCallMessage.callId, this)
        }
    }

    private fun refuseCall() {
        if (operateType != null) {
            return
        }
        operateType = LiveConst.AnswerType.REFUSE.apply {
            mViewModel.answerCall(mCallMessage.callId, this)
        }
    }

    override fun onBackPressed(): Boolean {
        if (!isCreated() || activity?.isFinishing != false) {
            return true
        } else if (operateType != null) {
            return true
        }

        refuseCall()

        return true
    }

    fun setOnCallAnswerListener(l: OnCallAnswerListener) {
        this.mOnCallAnswerListener = l
    }
}